<?php

// +----------------------------------------------------------------------
// | 私信
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\event\pos;

use app\common\event\Base;
use app\event\ucenter\User as UserEvent;
use app\model\pos\PosLevel as PosLevelModel;

use app\model\ucenter\User as UserModel;
use app\model\pos\PosTrade as PosTradeModel;
use app\model\pos\Pos as PosModel;
use app\model\ucenter\UserMoneyLog;
use think\facade\Db;
use think\Exception;

class Pos extends Base
{
    /**
     * 发送者
     * @var UserModel
     */
    protected UserModel $user;
    /**
     * 参数
     * @var array
     */
    protected array $param;

    protected $from;


    /**
     * 终端返现
     * @param array $param
     * @param UserModel $user
     */
    public function payback(): array
    {
        try {

            Db::startTrans();
            $this->_dealBack(30, 1, 29);
            $this->_dealBack(60, 2, 10);
            $this->_dealBack(90, 3, 10);
            $data['code'] = 0;
            Db::commit();
            $data['message'] = 'success';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 2;
            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }

    /**
     * 终端返现检查
     */
    public static function paybackCheck($pos)
    {
        if (!$pos) {
            throw new Exception('pos机不存在');
        }
        if (strtotime($pos['bind_time']) > (time() - 86400 * 30)) {
            //第一月的返佣阶段
            self::_dealBackPos($pos, 30, 1, 29);
        } elseif (strtotime($pos['bind_time']) > (time() - 86400 * 60)) {
            //第二月的返佣阶段
            self::_dealBackPos($pos, 60, 2, 10);
        } elseif (strtotime($pos['bind_time']) > (time() - 86400 * 90)) {
            //第三月的返佣阶段
            self::_dealBackPos($pos, 90, 3, 10);
        }
        return false;
    }

    /**
     * 终端返现检查
     */
    public function flow($pos,$order_id,$channel_id): array
    {
        try {
            Db::startTrans();
            if ($pos['cashback_user_id'] || $pos['buy_user_id']) {
                //参加返现
                if ($pos['cashback_user_id']) {
                    $user = UserModel::where('id', $pos['cashback_user_id'])->find();
                } else {
                    $user = UserModel::where('id', $pos['buy_user_id'])->find();
                    if ($pos['buy_user_id'] != $pos['user_id']) {
                        // 是否已经有过返
                        $first = UserMoneyLog::where('type', 91)->where('from_id',$pos['id'])->where('channel', $channel_id)->where('user_id', $user['id'])->find();
                        if ($first) {
                            // 首次之后给实际用户
                            $user = UserModel::where('id', $pos['user_id'])->find();
                        }
                    }
                }
                if ($user) {
                    // 流量费返现
                    $log = UserMoneyLog::where('order_id', $order_id)->where('from_id',$pos['id'])->where('type', 91)->where('channel', $channel_id)->where('user_id', $user['id'])->find();
                    if (!$log) {
                        //参加返现固定金额
                        $amount = 40;
//                            $user['my_balance'] = $user['my_balance'] + $data['amount'] / 100;
                        $user['my_balance'] = $user['my_balance'] + $amount;
                        $user->save();
                        UserEvent::money($amount, $user['id'], '流量返现（' . $pos['sn'] . '）', 91, $pos['user_id'], $order_id, 0, $channel_id,16);
                    }
                }
            }
            Db::commit();
            $data['code'] = 0;
            $data['message'] = 'success';
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $data['code'] = 2;
            $data['message'] = 'file:' . $e->getFile() . ',message:' . $e->getMessage() . 'li' . $e->getLine();
//				$data['message'] = $e->getMessage();
        }
        return $data;
    }


    protected function _dealBack($day, $no, $amount): void
    {
//        $start = date('Y-m-d 00:00:00',strtotime('-' . ($day ) . ' day'));
//        $end = date('Y-m-d 23:59:59',strtotime('-' . ($day -29) . ' day'));
//        // 查询激活时间区间的pos
//        $poses = PosModel::where('status', 1)
//            ->whereNotNull('user_id')->whereBetweenTime('bind_time', $start, $end)
//            ->select();

        $start = date('Y-m-d 00:00:00', strtotime('-' . ($day + 2) . ' day'));
        $end = date('Y-m-d 23:59:59', strtotime('-' . ($day + 1) . ' day'));
//两天内处理
        $poses = PosModel::where('status', 1)->whereNotNull('user_id')
            ->whereBetweenTime('bind_time', $start, $end)
            ->select();
        foreach ($poses as $index => $pos) {
            if ($pos['cashback_user_id'] || $pos['buy_user_id']) {
                //参加返现
                if ($pos['cashback_user_id']) {
                    $user = UserModel::where('id', $pos['cashback_user_id'])->find();
                } else {
                    $user = UserModel::where('id', $pos['buy_user_id'])->find();
                }
                $orderid = $pos['sn'] . 'X' . $no;
                if ($no > 1) {
                    $order_last = $pos['sn'] . 'X' . ($no - 1);
                }
                if ($user) {
                    if (
                        $no == 1
                        || ($no == 2 && $pos['pos_level_id'] > 1)
                        || ($no == 3 && $pos['pos_level_id'] > 2)
                    ) {
                        $log = UserMoneyLog::where('order_id', $orderid)->where('type', 92)
                            ->where('user_id', $user['id'])
                            ->where('from_id', $pos['id'])
//                            ->whereTime('create_time', '>', '-3 day')
                            ->find();
                        if ($no > 1) {
                            $order_last = $pos['sn'] . 'X' . ($no - 1);
                            $lastLog = UserMoneyLog::where('order_id', $order_last)->where('type', 92)
                                ->where('user_id', $user['id'])
                                ->where('from_id', $pos['id'])
//                                ->whereTime('create_time', '>', '-3 day')
                                ->find();
                            if (!$lastLog) {
                                continue;
                            }
                        }
                        if (!$log) {
                            $time1 = strtotime($pos['bind_time']) + ($day - 30) * 86400;
                            $time2 = strtotime($pos['bind_time']) + $day * 86400;
                            // 核实期间交易记录
                            $sum = PosTradeModel::where('pos_id', $pos['id'])
                                ->whereBetweenTime('trans_time', $time1, $time2)
                                ->where('trade_type', 1)
                                ->where('card_type', 2)
                                ->where('type', 1)
                                ->where('status', 1)
                                ->sum('amount');
                            if ($sum >= 10000) {
                                //参加返现
                                $user['my_balance'] = $amount + $user['my_balance'];
                                $user->save();
                                UserEvent::money($amount, $user['id'], '交易返现（' . $pos['sn'] . '）', 92, $pos['id'], $orderid,0,$pos['channel_id'],16);
                            }
                        }
                    }
                }
            }

        }
    }

    protected static function _dealBackPos($pos, $day, $no, $amount): void
    {
        if ($pos['cashback_user_id'] || $pos['buy_user_id']) {
            //参加返现
            if ($pos['cashback_user_id']) {
                $user = UserModel::where('id', $pos['cashback_user_id'])->find();
            } else {
                $user = UserModel::where('id', $pos['buy_user_id'])->find();
            }
            if ($user) {
                // 按用户pos等级
                if (
                    $no == 1
                    || ($no == 2 && $pos['pos_level_id'] > 1)
                    || ($no == 3 && $pos['pos_level_id'] > 2)
//                    || ($no == 3 && $pos['pos_level_id'] > 2)
                ) {
                    if ($no > 1) {
                        // 上次未返，后续暂停
                        $lastLog = UserMoneyLog::where('order_id', $pos['sn'] . 'X' . ($no - 1))->where('type', 92)
                            ->where('user_id', $user['id'])
                            ->where('from_id', $pos['id'])
                            ->find();
                        if (!$lastLog) {
                            return;
                        }
                    }

                    $orderid = $pos['sn'] . 'X' . $no;
                    $log = UserMoneyLog::where('order_id', $orderid)->where('type', 92)
                        ->where('user_id', $user['id'])
                        ->find();
                    if (!$log) {
                        $time1 = strtotime($pos['bind_time']) + ($day - 30) * 86400;
                        $time2 = strtotime($pos['bind_time']) + $day * 86400;
                        // 核实期间交易记录
                        $sum = PosTradeModel::where('pos_id', $pos['id'])
                            ->whereBetweenTime('trans_time', $time1, $time2)
                            // 借贷卡
                            ->where('trade_type', 1)
                            // 刷卡
                            ->where('card_type', 2)
                            //刷卡交易
                            ->where('type', 1)
                            ->where('status', 1)
                            ->sum('amount');
                        if ($sum >= 10000) {
                            //参加返现
                            $user['my_balance'] = $amount + $user['my_balance'];
                            $user->save();
                            UserEvent::money($amount, $user['id'], 'POS交易返现（' . $pos['sn'] . '）', 92, $user['id'], $orderid,0,$pos['channel_id'],16);
                        }
                    }
                }
            }

        }
    }

}
